<template>
  <div>
    <div
      class="farm-event-container"
      v-if="farmContainerStatus == 1"
    >
      <el-card body-style="padding:10px;">
        <div
          class="flex-wrap"
          style="margin-left: 10px"
        >
          <el-form
            :inline="true"
            :model="formInline"
            style="margin-bottom: -20px"
          >
            及简介
            <el-form-item label="作物类型">
              <el-select
                v-model="formInline.plantType"
                placeholder="请选择类型"
                clearable
              >
                <el-option
                  v-for="item in cropTypeOptions"
                  :key="item.plantCode"
                  :label="item.plantName"
                  :value="item.plantCode"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="排序">
              <el-select
                v-model="formInline.sortType"
                placeholder="请选择排序"
                clearable
              >
                <el-option
                  v-for="item in sortTypeOptions"
                  :key="item.sortCode"
                  :label="item.sortName"
                  :value="item.sortCode"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="种植人员">
              <el-select
                v-model="formInline.planter"
                placeholder="请选择种植人员"
                clearable
              >
                <el-option
                  v-for="item in plantersTypeOptions"
                  :key="item.planterCode"
                  :label="item.planterName"
                  :value="item.planterCode"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-input
                v-model.trim="formInline.keyWorks"
                placeholder="请输入要查询的关键字"
                @keydown.native.enter="onSubmit"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="onSubmit"
                :loading="queryStatus"
              >查询
              </el-button>
            </el-form-item>
          </el-form>
          <div
            class="flex-item-right"
            style="flex: 1"
          >
            <el-button
              type="primary"
              @click="handleClickEventDetail"
            >农事一览
            </el-button>
            <el-button
              type="primary"
              plain
              @click="handleClickAddPlant"
            >添加地块
            </el-button>
          </div>
        </div>
      </el-card>
      <el-card
        :style="{ marginTop: '10px', height: mainCardHeight + 'px' }"
        v-loading="tableLoading"
      >
        <div class="plant-tag-wrap">
          <div
            @click="handleClickAll"
            class="select-all-wrap"
          >
            <check-radio
              ref="allRadio"
              style="margin-top: -4px"
            />
            <div style="margin-left: 10px">全选</div>
          </div>
          <el-button
            type="primary"
            plain
            style="margin-left: 20px"
            :disabled="delBtnStatus"
          >批量种植
          </el-button>
          <el-button
            type="primary"
            plain
            style="margin-left: 20px"
            :disabled="delBtnStatus"
            @click="handleClickBatchTask"
          >批量下发任务
          </el-button>
          <el-button
            type="primary"
            plain
            style="margin-left: 20px"
            :disabled="delBtnStatus"
            @click="handleClickFarmEvent"
          >添加农事记录
          </el-button>
          <el-button
            type="primary"
            plain
            style="margin-left: 20px"
            :disabled="delBtnStatus"
            @click="handleClickBatchDelete"
          >删&nbsp;除
          </el-button>
          <div class="page-info-wrap">
            共<span class="child-span">{{ page.total }}</span>条&nbsp;&nbsp;&nbsp;&nbsp;
            <img
              :src="leftArrow"
              class="child-img"
              @click="handleClickPage(true)"
            />
            <span class="child-span">{{ page.pageNum }}</span>
            <img
              :src="rightArrow"
              class="child-img"
              @click="handleClickPage(false)"
            />
          </div>
        </div>
        <div ref="acreContainerWrap">
          <div
            v-if="isShowLandItems"
            class="land-container"
          >
            <acre-card
              @openFarmDetail="openFarmDetail"
              @radioSelect="currentSelectRadio"
              class="acre-card-item"
              v-for="item in acreItemList"
              :key="item.key"
              :ref="'acreItem_' + item.id"
            />
          </div>
        </div>
      </el-card>
    </div>
    <div
      clas="farm-browse-container"
      v-if="farmContainerStatus == 2"
    >
      <farm-browse @changePage="changeFarmContainer" />
    </div>
    <div
      clas="farm-browse-container"
      v-if="farmContainerStatus == 3"
    >
      <!-- 传值给详情页 -->
      <massifDetails
        :listParames="listParames"
        @changePage="changeFarmContainer"
        ref="massifDetails"
      />
    </div>
    <div
      clas="farm-browse-container"
      v-if="farmContainerStatus == 4"
    >
      <add-land
        @changePage="changeFarmContainer"
        @refresh="getPlantList"
      />
    </div>
    <task-dialog ref="taskDialog" />
    <farm-record-dialog ref="farmRecordDialog" />
    <batch-task-dialog ref="batchTaskDialog" />
  </div>
</template>
<script>
import PubSub from 'pubsub-js'
import {
  FARM_EVENT_OPEN_DIALOG,
  FARM_TASK_OPEN_DIALOG
} from '@/utils/publishId'
import radio from "./component/radio";
import acreCard from "./component/acre-card";
import farmBrowse from "./component/farmBrowse";

import plotDetails from "./component/plotDetails"

import batchTaskDialog from './component/batchTaskDialog'
import farmRecordDialog from "./component/farmRecordDialog"
import taskDialog from "./component/taskDialog"
import massifDetails from "./component/massifDetails"
import addLand from "./component/addLand";
import {
  typelistMaterial
} from "@/api/material";
import {
  queryPlanters,
  queryTaskList,
  queryTaskType,
  queryFarmingSort
} from "@/api/affairs"
import { getUUID } from "../../../utils";

export default {
  components: {
    "check-radio": radio,
    "acre-card": acreCard,
    "farm-browse": farmBrowse,

    "plot-details": plotDetails,

    "farm-record-dialog": farmRecordDialog,
    "batch-task-dialog": batchTaskDialog,
    "task-dialog": taskDialog,
    "massifDetails": massifDetails,
    "add-land": addLand
  },
  data () {
    return {
      isShowLandItems: false,
      farmEventPubSub: null,
      farmTaskPubSub: null,
      delBtnStatus: false,
      farmContainerStatus: 1, // 1 农事管理 2农事一览 3详情 4添加
      currentSelectItems: [],
      leftArrow: require("@/assets/img/event/left-arrow.png"),
      rightArrow: require("@/assets/img/event/right-arrow.png"),
      isCheckAll: false,
      queryStatus: false,
      tableLoading: false,
      mainCardHeight: 0,
      taskTypeList: [],
      acreWidth: 0,
      page: {
        total: 10,
        pageSize: 10,
        pageNum: 1,
        pages: 0
      },
      cropTypeOptions: [], // 作物类型
      sortTypeOptions: [], // 排序类型
      plantersTypeOptions: [], // 种植人员
      acreItemList: [], // 地块列表
      formInline: {
        plantType: '',
        sortType: '',
        planter: '',
        keyWorks: ''
      },
      listParames: {}//接收列表取的参数
    }
  },

  watch: {
    currentSelectItems: {
      handler (n, o) {
        this.delBtnStatus = n && n.length > 0 ? false : true
      },
      deep: true,
      immediate: true
    }
  },
  created () {
    this.$dynamic(
      window,
      document,
      184,
      (height) => {
        this.mainCardHeight = height
      }
    );
    this.$nextTick(() => {
      this.acreWidth = (this.$refs.acreContainerWrap.clientWidth - 40 - 52) / 5
    })
  },
  mounted () {
    this.farmEventPubSub = PubSub.subscribe(FARM_EVENT_OPEN_DIALOG, (msg, data) => {
      const { show, type, item } = data
      this.$refs.farmRecordDialog.show(show, type, item)
    })
    this.farmTaskPubSub = PubSub.subscribe(FARM_TASK_OPEN_DIALOG, (msg, data) => {
      const { show, type, item, massId } = data
      this.$refs.taskDialog.show(show, type, item, massId)
    })
    this.getPlantList()
    this.getAllTypeList()
  },
  methods: {
    async getPlantList () {
      this.acreItemList = []
      this.tableLoading = true
      this.isShowLandItems = false
      const params = {
        pageSize: this.page.pageSize,
        pageNum: this.page.pageNum
      }
      if (this.formInline.keyWorks && this.formInline.keyWorks != '') {
        params['landName'] = this.formInline.keyWorks
      }
      if (this.formInline.planter && this.formInline.planter != '') {
        params['plantPerson'] = this.formInline.planter
      }
      if (this.formInline.sortType && this.formInline.sortType != '') {
        params['sort'] = this.formInline.sortType * 1
      }
      if (this.formInline.plantType && this.formInline.plantType != '') {
        params['landType'] = this.formInline.plantType
      }
      const response = await queryTaskList(params)
      const { code, data, msg } = response.data
      // console.log(code, data, msg)
      this.page.total = data.total
      this.page.pageNum = data.pageNum
      this.page.pageSize = data.pageSize
      this.page.pages = data.pages
      if (code == 200) {
        if (data.list && data.list.length > 0) {
          data.list.forEach(item => {
            const obj = {
              id: item.id,
              key: getUUID(),
              width: this.acreWidth,
              flag: 1,
              label: item.landName,
              address: item.landAddress,
              area: item.landArea,
              name: item.plantPersonName,
              imgUrl: item.landImg,
              status: {
                flag: '1',
                statusColor: item.plantName && item.plantName != '' ? "#fc4c03" : "#c60814",
                statusLabel: item.plantName
              }
            }
            // console.log("this.acreWidth",this.acreWidth)
            this.acreItemList.push(obj)
          })
        }
        this.tableLoading = false
        this.isShowLandItems = true
        this.$nextTick(() => {
          this.acreItemList.forEach(item => {
            this.$refs['acreItem_' + item.id][0].setData(item)
          })
        })
      } else {
        this.isShowLandItems = false
        this.tableLoading = false
        this.$message({ type: "error", message: msg })
      }
      // {id:1,width: this.acreWidth, flag:1, label:"测试1", address:"测试", area:"13123", name:"测试", imgUrl:"", status:{flag:'1', statusColor: '#ffba02', statusLabel: 'afasdf'}},
    },
    getAllTypeList () {
      const loading = this.$load(this)
      let responseArray = [queryFarmingSort(), typelistMaterial({
        goodType: "farm_good",
        level: 3,
        parentId: 3
      }), queryPlanters(), queryTaskType()]
      Promise.all(responseArray).then(res => {
        this.sortTypeOptions = []
        if (res[0].data.code == 200 && res[0].data.data && res[0].data.data.length > 0) {
          res[0].data.data.forEach(item => {
            const obj = {
              sortCode: item.dictValue,
              sortName: item.dictLabel
            }
            this.sortTypeOptions.push(obj)
          })
        }
        if (res[1].data.code == 200 && res[1].data.data && res[1].data.data.length > 0) {
          this.cropTypeOptions = []
          res[1].data.data.forEach(item => {
            const obj = {
              plantCode: item.id,
              plantName: item.goodName
            }
            this.cropTypeOptions.push(obj)
          })
        }
        if (res[2].data.code == 200 && res[2].data.data && res[2].data.data.length > 0) {
          this.plantersTypeOptions = []
          res[2].data.data.forEach(item => {
            const obj = {
              planterCode: item.userId,
              planterName: item.userName
            }
            this.plantersTypeOptions.push(obj)
          })
        }
        //农事类型
        if (res[3].data.code == 200 && res[3].data.data && res[3].data.data.length > 0) {
          this.taskTypeList = []
          res[3].data.data.forEach(item => {
            const obj = {
              formCode: item.dictValue,
              formName: item.dictLabel
            }
            this.taskTypeList.push(obj)
          })
        }
        loading.close()
      }).catch(err => {
        loading.close()
        this.$message({ type: "error", message: "获取options失败：" + err })
      })
    },
    onSubmit () {
      this.getPlantList()
    },
    openFarmDetail (object) {
      this.farmContainerStatus = 3; // 1 农事管理 2农事一览3详情
      // sessionStorage.setItem("massifDetails", JSON.stringify(object))
      this.$nextTick(() => {
        this.$refs.massifDetails.setDetailInfo(object)
      })
    },
    changeFarmContainer (type) {
      this.farmContainerStatus = type
      this.$dynamic(
        window,
        document,
        184,
        (height) => {
          this.mainCardHeight = height
        }
      );
      this.$nextTick(() => {
        this.acreWidth = (this.$refs.acreContainerWrap.clientWidth - 40 - 52) / 5
        this.getPlantList()
      })
    },
    handleClickEventDetail () {
      this.farmContainerStatus = 2
      // this.$router.push({ name: 'farmBrowse' })
    },
    handleClickBatchDelete () {
      this.$confirm('此操作将永久删除选中内容, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$load(this)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        loading.close()
        this.getPlantList()
      }).catch(() => {
      });
    },
    handleClickBatchTask () {
      this.$refs.batchTaskDialog.show(true, this.taskTypeList, this.currentSelectItems)
    },
    handleClickFarmEvent () {
      this.$refs.farmRecordDialog.show(true, 'add', { ids: this.currentSelectItems })
    },
    handleClickAddPlant () {
      // this.$message({type:"info",message:"敬请期待..."})
      this.farmContainerStatus = 4
    },
    currentSelectRadio (status, row) {
      if (status) {
        this.currentSelectItems.push(row)
      } else {
        this.currentSelectItems.splice(this.currentSelectItems.findIndex(item => item.id == row.id), 1)
      }
      this.isCheckAll = this.currentSelectItems.length == this.acreItemList.length
      this.$refs.allRadio.switch(this.isCheckAll)
      // console.log("currentSelectItems",this.currentSelectItems)
    },
    handleClickPage (status) {
      if (status) {
        // console.log("向前翻一页")
        if (this.page.pageNum == 1) {
          this.$message({ type: "warn", message: "没更更多页了" })
          return
        }
        this.page.pageNum -= 1
      } else {
        // console.log("向后翻一页")
        if (this.page.pages == this.page.pageNum) {
          this.$message({ type: "warn", message: "没更更多页了" })
          return
        }
        this.page.pageNum += 1
      }
      this.getPlantList()
    },
    handleClickAll () {
      if (this.acreItemList.length == 0) {
        return
      }
      this.isCheckAll = !this.isCheckAll
      this.$refs.allRadio.switch(this.isCheckAll)
      this.acreItemList.forEach(item => {
        this.$refs['acreItem_' + item.id][0].setRadioChecked(this.isCheckAll)
      })
      if (this.isCheckAll == true) {
        this.currentSelectItems = this.$cloneDeep(this.acreItemList)
      } else {
        this.currentSelectItems = []
      }
    }
  },
  beforeDestroy () {
    this.$unResize(window)
    PubSub.unsubscribe(this.farmEventPubSub)
    PubSub.unsubscribe(this.farmTaskPubSub)
  }
}

</script>
<style scoped>
.land-container {
  display: flex;
  flex-wrap: wrap;
}

.flex-wrap {
  display: flex;
  align-items: center;
}

.select-all-wrap {
  user-select: none;
  display: flex;
  align-items: center;
}

.flex-item-right {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.plant-tag-wrap {
  user-select: none;
  display: flex;
  align-items: center;
}

.page-info-wrap {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.page-info-wrap .child-span {
  display: inline-block;
  text-align: center;
  padding: 0 10px;
}

.page-info-wrap .child-img {
  width: 24px;
  height: 24px;
}

.land-container .acre-card-item {
  margin-top: 20px;
  margin-right: 20px;
}

.land-container .acre-card-item:nth-child(5n + 5) {
  margin-right: 0px;
}
</style>
